"use strict";

const Controller = require("egg").Controller;
const _ = require("lodash");

class RegisterControllerController extends Controller {

    /**
     * @api {post} /x/v1/auth/registerByEmail 邮箱注册
     * @apiName 邮箱注册
     * @apiGroup 用户注册
     * @apiVersion 1.0.0
     *
     * @apiParam {string} email 邮箱
     * @apiParam {string} password 密码
     * @apiParam {string} captcha 验证码
     *
     */
    async registerByEmail() {
        // TODO: 查询设置中的邮箱注册开关

        const body = this.ctx.request.body;
        const email = _.get(body, "email");
        const password = _.get(body, "password");

        await this.service.validate.verifyEmail(email);

        await this.service.validate.verifyPassword(password);

        const user = await this.ctx.model.Users.build({ email, password });

        if (await user.checkEmail(email)) {
            this.ctx.throw(400, "邮箱已被使用", { user: "user" });
        }

        await user.save();

        const token = this.service.jsonWebToken.signLoginToken(user.id);

        this.ctx.returnBody(200, "邮箱注册成功", token);
    }

    async registerByPhone() {
        //
    }

}

module.exports = RegisterControllerController;
